package cn.topcodes.tcsf.codegen.ui;

import cn.topcodes.tcsf.codegen.domain.entity.Entity;
import cn.topcodes.tcsf.codegen.domain.entity.Field;
import cn.topcodes.tcsf.codegen.utils.ScreenUtil;
import cn.topcodes.tcsf.codegen.utils.SqliteOpenHelper;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.stmt.QueryBuilder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author 大爱阳哥
 */
public class SetFieldDialog extends javax.swing.JDialog {
    
    private int entityId;


    public SetFieldDialog(java.awt.Frame parent, boolean modal,int entityId) {
        super(parent, modal);
        initComponents();
        ScreenUtil.initLocation(this);
        
        ImageIcon imageIcon = new ImageIcon("resource/images/logo.png");  
        this.setIconImage(imageIcon.getImage());  
        
        this.entityId = entityId;
        try {
            loadData();
        }catch(Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载字段信息失败:" + e.getMessage());
        }
    }
    
    private void loadData() throws SQLException {
        Entity entity = (Entity) SqliteOpenHelper.getEntityDao().queryForId(entityId);
        ForeignCollection<Field> mfields = entity.getFields();
        List<Field> fields = new ArrayList<Field>();
        for(Field field : mfields) {
            fields.add(field);
        }
        
        String[] header = { "字段名称","*实体属性", "*显示名称", "物理类型","Java类型", "*允许为空", "*唯一",
                            "*显示字段","*表单字段","*查询字段","*查询条件"};   
        Object[][] row = new Object[fields.size()][11];
        for(int i = 0 ; i < fields.size() ; i ++ ) {
            row[i][0] = fields.get(i).getFieldName();
            row[i][1] = fields.get(i).getPropertyName();
            row[i][2] = fields.get(i).getDisplayName();
            row[i][3] = fields.get(i).getDbDataType();
            row[i][4] = fields.get(i).getJdbcDataType();
            row[i][5] = fields.get(i).isAllowNull();
            row[i][6] = fields.get(i).isUnique();
            row[i][7] = fields.get(i).isDisplayField();
            row[i][8] = fields.get(i).isFormField();
            row[i][9] = fields.get(i).isQueryField();
            row[i][10] = fields.get(i).getQueryCondition();
        }
        final DefaultTableModel dtm = new DefaultTableModel(){   
            @Override  
            public Class<?> getColumnClass(int c){   
                switch(c) {
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        return String.class;
                    case 5:
                    case 6:
                    case 7:
                    case 8:
                    case 9:
                        return Boolean.class;
                    case 10:
                        return String.class;
                }
                return Object.class;
            }   
            @Override  
            public boolean isCellEditable(int x, int y){   
                switch(y) {
                    case 0:
                        return false;
                    case 1:
                    case 2:
                        return true;
                    case 3:
                    case 4:
                        return false;
                    case 5:
                    case 6:
                    case 7:
                    case 8:
                    case 9:
                    case 10:
                        return true;
                }
                return false;
            }   
        };
        dtm.setDataVector(row,header);
        tbFields.setModel(dtm);
        tbFields.addMouseListener(new MouseAdapter() {
            
            @Override
            public void mouseClicked(MouseEvent e) {
                int sr;
                if ((sr = tbFields.getSelectedRow()) == -1) {
                    return;
                }
                if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                    String fieldName = (String)dtm.getValueAt(sr, 0);
                    FieldDetailDialog dlg = new FieldDetailDialog(null,true,fieldName,entityId);
                    dlg.setVisible(true);
                }
            }
            
        });
        
        JComboBox combo = new JComboBox();
        combo.addItem( "EQ" );
        combo.addItem( "NEQ" );
        combo.addItem( "LIKE" );
        combo.addItem( "LLIKE" );
        combo.addItem( "RLIKE" );
        combo.addItem( "GT" );
        combo.addItem( "GTE" );
        combo.addItem( "LT" );
        combo.addItem( "LTE" );
        combo.addItem( "IN" );
        combo.addItem( "NIN" );
        tbFields.getColumnModel().getColumn(10).setCellEditor(new DefaultCellEditor(combo));
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbFields = new javax.swing.JTable();
        btnSave = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("设置字段");
        setResizable(false);

        tbFields.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tbFields);
        if (tbFields.getColumnModel().getColumnCount() > 0) {
            tbFields.getColumnModel().getColumn(1).setResizable(false);
            tbFields.getColumnModel().getColumn(2).setResizable(false);
            tbFields.getColumnModel().getColumn(3).setResizable(false);
            tbFields.getColumnModel().getColumn(4).setResizable(false);
            tbFields.getColumnModel().getColumn(5).setResizable(false);
            tbFields.getColumnModel().getColumn(6).setResizable(false);
            tbFields.getColumnModel().getColumn(7).setResizable(false);
            tbFields.getColumnModel().getColumn(8).setResizable(false);
        }

        btnSave.setText("保存");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnCancel.setText("取消");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 804, Short.MAX_VALUE)
                        .addComponent(btnSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnCancel))
                .addGap(8, 8, 8))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        Entity entity = null;
        try {
            entity = (Entity)SqliteOpenHelper.getEntityDao().queryForId(entityId);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "保存失败");
            return;
        }
        if(entity == null) {
            JOptionPane.showMessageDialog(this, "Entity不存在");
            return;
        }
        
        DefaultTableModel model = (DefaultTableModel)this.tbFields.getModel();
        
        Vector dataVector = model.getDataVector();
        Iterator dataVectorIterator = dataVector.iterator();
        while(dataVectorIterator.hasNext()) {
            Vector vector = (Vector) dataVectorIterator.next();
            String fieldName = (String)vector.get(0);
            String propertyName = (String)vector.get(1);
            String displayName = (String)vector.get(2);
            String dbDataType = (String) vector.get(3);
            String jdbcDataType = (String) vector.get(4);
            boolean allowNull = (boolean) vector.get(5);
            boolean isUnique = (boolean) vector.get(6);
            boolean isDisplayField = (boolean) vector.get(7);
            boolean isFormField = (boolean) vector.get(8);
            boolean isQueryField = (boolean) vector.get(9);
            String queryCondition = (String) vector.get(10);
            
            try {
                QueryBuilder qb = SqliteOpenHelper.getFieldDao().queryBuilder();
                qb.where().eq("field_name", fieldName).and().eq("entity_id", this.entityId);
                Field field = (Field) qb.queryForFirst();
                field.setEntity(entity);
                field.setFieldName(fieldName);
                field.setPropertyName(propertyName);
                field.setDisplayName(displayName);
                field.setDbDataType(dbDataType);
                field.setJdbcDataType(jdbcDataType);
                field.setAllowNull(allowNull);
                field.setUnique(isUnique);
                field.setDisplayField(isDisplayField);
                field.setFormField(isFormField);
                field.setQueryField(isQueryField);
                field.setQueryCondition(queryCondition);
                SqliteOpenHelper.getFieldDao().update(field);
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "保存失败:" + ex.getMessage());
            }
        }
        this.dispose();
    }//GEN-LAST:event_btnSaveActionPerformed

  
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnSave;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbFields;
    // End of variables declaration//GEN-END:variables
}
